package com.tencreat.mall.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tencreat.common.annotation.Log;
import com.tencreat.common.core.HttpResult;
import com.tencreat.common.core.controller.BaseController;
import com.tencreat.common.core.domain.AjaxResult;
import com.tencreat.common.core.domain.model.ReqIdParam;
import com.tencreat.common.core.domain.model.ReqIdsParam;
import com.tencreat.common.enums.BusinessType;
import com.tencreat.common.utils.poi.ExcelUtil;
import com.tencreat.domain.pt.MallPtGoods;
import com.tencreat.domain.pt.MallPtUsers;
import com.tencreat.domain.pt.vo.*;
import com.tencreat.domain.pt.dto.PtHistoryInfoDTO;
import com.tencreat.domain.pt.dto.PtHistoryListDTO;
import com.tencreat.domain.pt.dto.PtPeriodsDTO;
import com.tencreat.domain.pt.dto.PtUpdateTimeDto;
import com.tencreat.domain.pt.dto.*;
import com.tencreat.service.pt.IMallPtGoodsService;
import com.tencreat.service.pt.IMallPtService;
import com.tencreat.service.pt.IMallPtUsersService;
import com.tencreat.service.pt.scheduler.CommonScheduler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 拼团商品Controller
 *
 * @author tencreat
 * @date 2021-11-08
 */
@Api(tags = "后台PC拼团api")
//@RestController
@RequestMapping("/api/pc/ptGoods")
@Slf4j
public class MallPtGoodsController extends BaseController {
    //@Autowired
    private IMallPtGoodsService mallPtGoodsService;

    //@Autowired
    private IMallPtService ptService;

    //@Autowired
    private IMallPtUsersService ptUsersService;

    /**
     * 查询拼团商品列表
     */
    @ApiOperation(value = "查询拼团商品列表")
    @GetMapping("/list")
    public HttpResult<IPage<ResPtGoodsListPCVO>> list(@ApiParam("分页页码") @RequestParam Integer pageNum,
                                                      @ApiParam("分页大小") @RequestParam Integer pageSize,
                                                      @ApiParam("拼团编号") @RequestParam(required = false) String ptSn,
                                                      @ApiParam("商品id") @RequestParam(required = false) Long goodsId,
                                                      @ApiParam("专区id") @RequestParam(required = false) Integer zoneId,
                                                      @ApiParam("开奖状态") @RequestParam(required = false) Integer lotteryStatus,
                                                      @ApiParam("商品分类") @RequestParam(required = false) Integer goodsType,
                                                      @ApiParam("商品状态") @RequestParam(required = false) Integer goodsStarts
    ) {
        Page<ResPtGoodsListPCVO> page = new Page<>(pageNum, pageSize);
        return HttpResult.ok(mallPtGoodsService.list(page, ptSn, goodsId, zoneId, lotteryStatus, goodsType, goodsStarts));
    }

    /**
     * 导出拼团商品列表
     */
//    @ApiOperation(value = "导出拼团商品列表")
    @PreAuthorize("@ss.hasPermi('system:goods:export')")
    @Log(title = "拼团商品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public AjaxResult export(MallPtGoods mallPtGoods) {
        List<MallPtGoods> list = mallPtGoodsService.selectMallPtGoodsList(mallPtGoods);
        ExcelUtil<MallPtGoods> util = new ExcelUtil<MallPtGoods>(MallPtGoods.class);
        return util.exportExcel(list, "goods");
    }

    /**
     * 获取拼团商品详细信息
     */
//    @ApiOperation(value = "获取拼团商品详细信息")
    @PreAuthorize("@ss.hasPermi('system:goods:query')")
    @PostMapping(value = "/getInfo")
    public HttpResult<MallPtGoods> getInfo(@RequestBody ReqIdParam id) {
        return HttpResult.ok(mallPtGoodsService.selectMallPtGoodsById(id));
    }

    /**
     * 新增拼团商品
     */
    @ApiOperation(value = "新增拼团商品")
    @PreAuthorize("@ss.hasPermi('system:goods:add')")
    @Log(title = "拼团商品", businessType = BusinessType.INSERT)
    @PostMapping(value = "/batchAdd")
    public HttpResult<Boolean> batchAdd(@Validated @RequestBody List<PtGoodAddDTO> vo) throws SchedulerException {
        return to(mallPtGoodsService.batchAdd(vo, getLoginCheck()));
    }

    /**
     * 修改拼团商品
     */
//    @ApiOperation(value = "修改拼团商品")
    @PreAuthorize("@ss.hasPermi('system:goods:edit')")
    @Log(title = "拼团商品", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/edit")
    public HttpResult<Boolean> edit(@RequestBody MallPtGoods mallPtGoods) {
        return to(mallPtGoodsService.updateMallPtGoods(mallPtGoods));
    }

    /**
     * 删除拼团商品
     */
    @ApiOperation(value = "删除拼团商品")
    @PreAuthorize("@ss.hasPermi('system:goods:remove')")
    @Log(title = "拼团商品", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    public HttpResult<Boolean> remove(@RequestBody ReqIdParam id) {
        return to(ptService.deleteMallPtById(id));
    }

    /**
     * 拼团开启下一期
     */
    @ApiOperation("拼团开启下一期")
    @Log(title = "拼团开启下一期", businessType = BusinessType.INSERT)
    @PostMapping("/startNextEpisode")
    public HttpResult<?> startNextEpisode(@Validated @RequestBody PtStartNextDTO vo) throws SchedulerException {
        return ptService.startNextEpisode(vo, getLoginCheck());
    }


    /*@ApiOperation("拼团新增下一期(new)")
    @Log(title = "拼团新增下一期(new)", businessType = BusinessType.INSERT)
    @PostMapping("/startNextNewEpisode")
    public HttpResult<?> startNextNewEpisode(@Validated @RequestBody PtAdminStartNextVO vo) throws SchedulerException {
        return ptService.startNextNewEpisode(vo, getLoginCheck());
    }*/

    @ApiOperation("查询后台拼团累计信息")
    @PostMapping("/queryPtAdminInfo")
    public HttpResult<ResAdminPtInfoVo> queryPtAdminInfo() {
        return HttpResult.ok(ptService.queryPtAdminInfo());
    }

    /**
     * 添加参与人数
     */
    @ApiOperation(value = "添加参与人数")
    @PreAuthorize("@ss.hasPermi('system:pt:edit')")
    @Log(title = "添加参与人数", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/addPtNumber/{id}/{count}")
    public HttpResult<Boolean> addPtNumber(@PathVariable String id,
                                           @PathVariable String count) {
        return to(ptService.addPtNumber(id, count));
    }


    //test addJob
    @GetMapping("/addJobDemo")
    public HttpResult<?> cronDemo(@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date date,
                                  @RequestParam String name,
                                  @RequestParam String group) throws SchedulerException {
//        return CommonScheduler.ptJob(date, name, group);
        return null;
    }

    //test removeJob
//    @GetMapping("/removeJobDemo")
    public HttpResult<?> removeDemo(@RequestParam String name,
                                    @RequestParam String group) throws SchedulerException {
        return CommonScheduler.removeJob(name, group);
    }

    @ApiOperation("开奖用户列表")
    @GetMapping("/lotteryUsersList")
    public HttpResult<IPage<Map<String, Object>>> lotteryUsersList(
            @ApiParam("拼团id") @RequestParam Integer ptId,
            @ApiParam("用户id(uuid)") @RequestParam(required = false) Long uuid,
            @ApiParam("用户手机号") @RequestParam(required = false) String phone,
            @ApiParam("列表类型,必中1,选中2,待选择3") @RequestParam Integer type,
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize) {
        Page<Map<String, Object>> page = new Page<>(pageNum, pageSize);
        return HttpResult.ok(ptUsersService.lotteryUsersList(page, ptId, uuid, phone, type));
    }


    @ApiOperation("拼团批量选中/取消")
    @PostMapping("/ptBatchCancelSelected")
    public HttpResult<Boolean> ptBatchCancelSelected(@RequestBody ReqIdsParam ids,
                                                     @ApiParam("拼团id") @RequestParam Long ptId,
                                                     @ApiParam("2选中,3取消") @RequestParam Integer type
    ) {
        List<MallPtUsers> list = new ArrayList<>();
        for (Long id : ids.getId()) {
            MallPtUsers ptUsers = ptUsersService.lambdaQuery().eq(MallPtUsers::getPtId, ptId).eq(MallPtUsers::getUuid, id).one();
            if (ptUsers == null) {
                return HttpResult.error();
            }
            if (type == 2) {
                ptUsers.setInternalLottery(2);
            } else if (type == 3) {
                ptUsers.setInternalLottery(3);
            }
            list.add(ptUsers);
        }

        return to(ptUsersService.updateBatchById(list));
    }


    @ApiOperation("拼团历史记录")
    @GetMapping("/ptHistoricalRecord")
    public HttpResult<IPage<Map<String, Object>>> ptHistoricalRecord(
            @ApiParam("商品id") @RequestParam Integer goodsId,
            @ApiParam("开奖时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date time,
            @ApiParam("专区id") @RequestParam(required = false) Integer period,
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize) {
        Page<Map<String, Object>> page = new Page<>(pageNum, pageSize);
        return HttpResult.ok(ptUsersService.ptHistoricalRecord(page, goodsId, time, period));
    }

    @ApiOperation("拼团详情")
    @GetMapping("/ptDetail")
    public HttpResult<IPage<Map<String, Object>>> ptDetail(@ApiParam("拼团id") @RequestParam Integer ptId,
                                                           @RequestParam Integer pageNum,
                                                           @RequestParam Integer pageSize) {
        Page<Map<String, Object>> page = new Page<>(pageNum, pageSize);

        return HttpResult.ok(ptUsersService.ptDetail(page, ptId));
    }

    @ApiOperation("拼团开奖活动信息")
    @GetMapping("/lotteryDetailInfo")
    public HttpResult<Map<String, Object>> lotteryDetailInfo(@ApiParam("拼团id") @RequestParam Integer ptId) {
        return HttpResult.ok(ptUsersService.lotteryDetailInfo(ptId));
    }

    @ApiOperation("PC奖金池")
    @GetMapping("/getBonusPools")
    public HttpResult<IPage<ResBonusPoolPCVO>> getBonusPools(@ApiParam("分页页码") @RequestParam(required = false) Integer pageNum,
                                                             @ApiParam("分页大小") @RequestParam(required = false) Integer pageSize) {
        Page<ResBonusPoolPCVO> page = new Page<>(1, 9999);
        return HttpResult.ok(ptService.getBonusPools(page));
    }

    @ApiOperation("奖金池展示所有中奖用户")
    @GetMapping("/getAllBonusUser")
    public HttpResult<List<ResUserBonusPoolPCVO>> getBonusPools(@ApiParam("奖金池id") @RequestParam Integer id) {
        return HttpResult.ok(ptService.getAllBonusUser(id));
    }


    @ApiOperation("PC查询收益记录")
    @GetMapping("/getEarningsRecord")
    public HttpResult<IPage<Map<String, Object>>> getEarningsRecord(
            @ApiParam("用户id") @RequestParam(required = false) Integer uuid,
            @ApiParam("用户手机号") @RequestParam(required = false) String mobile,
            @ApiParam("收益类型") @RequestParam(required = false) Integer type,
            @ApiParam("开奖时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date sendTime,
            @ApiParam("发放状态") @RequestParam(required = false) Integer status,
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize
    ) {
        Page<Map<String, Object>> page = new Page<>(pageNum, pageSize);
        return HttpResult.ok(ptService.getEarningsRecord(page, uuid, mobile, type, sendTime, status));
    }

    @ApiOperation("查询拼团详情期数列表")
    @PostMapping("/queryPtPeriodsList")
    public HttpResult<List<ResPtPeriodsVo>> queryPtPeriodsList(@RequestBody PtPeriodsDTO dto) {
        return HttpResult.ok(ptService.queryPtPeriodsList(dto));
    }

    @ApiOperation("修改拼团期数")
    @Log(title = "修改拼团期数", businessType = BusinessType.UPDATE)
    @PostMapping("/updatePtTime")
    public HttpResult<?> updatePtTime(@RequestBody PtUpdateTimeDto dto) {
        return ptService.updatePtTime(dto);
    }


    @ApiOperation("删除拼团期数")
    @Log(title = "删除拼团期数", businessType = BusinessType.DELETE)
    @DeleteMapping("/removePt")
    public HttpResult<?> removePt(@RequestBody PtPeriodsDTO dto) {
        return HttpResult.ok(ptService.removePt(dto));
    }

    @ApiOperation("查询拼团历史记录")
    @PostMapping("/queryPtHistoryList")
    public HttpResult<IPage<ResAdminPtHistoryVo>> queryPtHistoryList(@RequestBody PtHistoryListDTO dto) {
        return HttpResult.ok(ptService.queryPtHistoryList(dto));
    }

    @Log(title = "导出拼团历史记录", businessType = BusinessType.EXPORT)
    @PostMapping("exportPtHistoryList")
    public AjaxResult exportPtHistoryList(@RequestBody PtHistoryListDTO dto) {
        dto.setPageNum(1L);
        dto.setPageSize(Long.MAX_VALUE);
        IPage<ResAdminPtHistoryVo> page = ptService.queryPtHistoryList(dto);
        ExcelUtil<ResAdminPtHistoryVo> util = new ExcelUtil<>(ResAdminPtHistoryVo.class);
        return util.exportExcel(page.getRecords(), "PtHistory");
    }


    @ApiOperation("查询拼团历史记录详细用户信息")
    @PostMapping("/queryPtHistoryInfoList")
    public HttpResult<IPage<ResAdminPtHistoryInfoVo>> queryPtHistoryInfoList(@RequestBody PtHistoryInfoDTO dto) {
        return HttpResult.ok(ptService.queryPtHistoryInfoList(dto));
    }

    @Log(title = "导出拼团历史记录详细用户信息", businessType = BusinessType.EXPORT)
    @ApiOperation("导出拼团历史记录详细用户信息")
    @PostMapping("exportPtHistoryInfoList")
    public AjaxResult exportPtHistoryInfoList(@RequestBody PtHistoryInfoDTO dto) {
        dto.setPageNum(1L);
        dto.setPageSize(Long.MAX_VALUE);
        IPage<ResAdminPtHistoryInfoVo> page = ptService.queryPtHistoryInfoList(dto);
        ExcelUtil<ResAdminPtHistoryInfoVo> util = new ExcelUtil<>(ResAdminPtHistoryInfoVo.class);
        return util.exportExcel(page.getRecords(), "PtHistoryInfo");
    }
}
